package sdk

import (
	"encoding/base64"
	"encoding/json"
	"log"
)

//打包成为平台的http消息
func Decode(raw []byte) (base *GatewayProtoBase, err error) {
	base = &GatewayProtoBase{}
	err = json.Unmarshal(raw, base)
	return
}

// decode base64, then to UserOnlineStatus
func DecodeBassNew(raw []byte) (base *UserOnlineStatus, err error) {

	base = &UserOnlineStatus{}
	err = json.Unmarshal(raw, base)
	return
}

// decode base64, then to UserOnlineStatus
func DecodeBase64(raw []byte) (base *GatewayProtoBase, err error) {
	newRaw, err := base64.StdEncoding.DecodeString(string(raw))
	//newRaw, err := base64.URLEncoding.DecodeString(string(raw))
	if err != nil {
		log.Printf("sdk Decode data from platform error: %v", err)
		return
	}

	base = &GatewayProtoBase{}
	base.Data = newRaw
	//err = json.Unmarshal(newRaw, base)
	return
}

func DecodeBase64New(raw []byte) (base *PostResultNew, err error) {
	base = &PostResultNew{}
	err = json.Unmarshal(raw, base)
	if err != nil {
		log.Printf("DecodeBase64New => Unmarshal error: %v", err)
	}
	newData, err := base64.StdEncoding.DecodeString(base.Data.(string))
	//newRaw, err := base64.URLEncoding.DecodeString(string(raw))
	if err != nil {
		log.Printf("DecodeBase64New => sdk Decode data from platform error: %v", err)
		return
	}

	base.Data = newData
	return
}

//打包成为平台的http消息
func DecodeAssign(raw []byte,base interface{}) (err error) {

	err = json.Unmarshal(raw, base)

	return
}

//解析平台发送过来的协议
func Encode(code int, message string, raw []byte) (bytes []byte, err error) {
	base := &GatewayProtoBase{
		Code:    code,
		Message: message,
		Data:    raw,
	}
	bytes, err = json.Marshal(base)
	return
}
